﻿using BrightIdeasSoftware;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static WindowsFormsApp1.UcFastObjectListView;

namespace WindowsFormsApp1
{
    public partial class UcFoLsv : UserControl
    {
        public UcFoLsv()
        {
            InitializeComponent();

            fastOLsv.RowHeight = 40; //行高
            fastOLsv.UseCompatibleStateImageBehavior = false;
            fastOLsv.UseFiltering = true;//过滤器
            fastOLsv.FullRowSelect = true;//整行选择
            fastOLsv.MultiSelect = true;  //选择多行
            fastOLsv.CellEditActivation = ObjectListView.CellEditActivateMode.SingleClick;//编辑模式
            fastOLsv.EmptyListMsg = "信息为空值";
            fastOLsv.AlternateRowBackColor = Color.FromArgb(192, 255, 192);//颜色交替出现
            fastOLsv.UseAlternatingBackColors = true;
            fastOLsv.AllowDrop = true;
            fastOLsv.DragSource = new SimpleDragSource();
            fastOLsv.DropSink = new RearrangingDropSink(true);

            fastOLsv.UseTranslucentHotItem = true;

            fastOLsv.Invalidate();
            fastOLsv.HotItemStyle.Overlay = new BusinessCardOverlay();
            fastOLsv.HotItemStyle = fastOLsv.HotItemStyle;
            //UseTranslucentHotItem
            //fastOLsv.group
            fastOLsv.GroupStateChanged += FastOLsv_GroupStateChanged;

            SetupColumns();
        }

        private void FastOLsv_GroupStateChanged(object sender, GroupStateChangedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        public FastObjectListView FastOLSV { get => fastOLsv; }


        public void SetDataSource(string[] fileNams, string rule = "")
        {
            List<LsvFileInfo> lsvInfo = new List<LsvFileInfo>();
            foreach (string item in fileNams)
            {
                LsvFileInfo file_info = new LsvFileInfo();
                file_info.FileName = Path.GetFileName(item);
                file_info.NewFileName = Path.GetFileName(item);
                file_info.Path = Path.GetDirectoryName(item);
                file_info.Status = "待操作";

                FileInfo fileInfo= new FileInfo(item);
                DateTime? XXX = GetCaptureTime(item);
                file_info.Size = FormatFileSize(fileInfo.Length);
                file_info.CrTime = fileInfo.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");//DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                file_info.MTime = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                file_info.Oper = "打开";
                lsvInfo.Add(file_info);
            }
            fastOLsv.SetObjects(lsvInfo);
        }

        #region 私有函数

        private void SetupColumns() 
        {

            this.原文件名.ImageGetter = GetImageIcon;
            this.原文件名.AspectGetter = delegate(object x) {
                LsvFileInfo xx=x as LsvFileInfo;
                Console.WriteLine(xx.FileName);
                return xx.FileName;
            };
            this.原文件名.MakeGroupies(
                new object[] { "1", "2", "3", "4"},
                new string[] { "Pay1111 to eat out", "Suggest take-away", "Passable", "Seek dinner invitation", "Hire as chef" },
                new string[] { "not", "hamburger", "toast", "beef", "chef" },
                new string[] {
                    "Pay good money -- or flee the house -- rather than eat their homecooked food",
                    "Offer to buy takeaway rather than risk what may appear on your plate",
                    "Neither spectacular nor dangerous",
                    "Try to visit at dinner time to wrangle an invitation to dinner",
                    "Do whatever is necessary to procure their services"
                },
                new string[] { "Call 911", "Phone PizzaHut", "", "Open calendar", "Check bank balance" }
              );



            this.操作.IsButton = true;
            this.操作.ButtonSizing = OLVColumn.ButtonSizingMode.FixedBounds;
            this.操作.ButtonSize = new Size(60, 26);
            this.操作.TextAlign = HorizontalAlignment.Center;
        }
        public string FormatFileSize(long size)
        {
            int[] limits = new int[] { 1024 * 1024 * 1024, 1024 * 1024, 1024 };
            string[] units = new string[] { "GB", "MB", "KB" };

            for (int i = 0; i < limits.Length; i++)
            {
                if (size >= limits[i])
                    return String.Format("{0:#,##0.##} " + units[i], ((double)size / limits[i]));
            }

            return String.Format("{0} bytes", size);
        }

        /// <summary>
        /// 获取图片的拍摄时间
        /// </summary>
        /// <param name="imagePath">图片文件路径</param>
        /// <returns>拍摄时间（如果存在），否则返回null</returns>
        public static DateTime? GetCaptureTime(string imagePath)
        {
            try
            {
                using (var image = Image.FromFile(imagePath))
                {
                    // 获取图片的所有属性
                    var propItems = image.PropertyItems;

                    // EXIF中拍摄时间的标签ID是36867
                    const int dateTimeOriginalTagId = 0x9003; // 36867

                    foreach (var prop in propItems)
                    {
                        if (prop.Id == dateTimeOriginalTagId)
                        {
                            // 将字节数组转换为字符串（EXIF时间格式："yyyy:MM:dd HH:mm:ss\0"）
                            string dateTimeString = System.Text.Encoding.ASCII.GetString(prop.Value);
                            dateTimeString = dateTimeString.Trim('\0'); // 去除结尾的空字符

                            // 解析时间字符串
                            if (DateTime.TryParseExact(
                                dateTimeString,
                                "yyyy:MM:dd HH:mm:ss",
                                System.Globalization.CultureInfo.InvariantCulture,
                                System.Globalization.DateTimeStyles.None,
                                out DateTime captureTime))
                            {
                                return captureTime;
                            }
                        }
                    }

                    // 如果没有找到拍摄时间，尝试获取修改时间
                    return File.GetLastWriteTime(imagePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取拍摄时间失败：{ex.Message}");
                return null;
            }
        }

        private Object GetImageIcon(Object row)
        {
            return 0;
        }
        private Object GroupKeyGetter(Object row)
        {
            return 0;
        }
        #endregion
    }
}
